package com.example.Controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.Mapper.FileMapper;
import com.example.ServiceImpl.FileServiceImpl;
import com.example.entity.UpLoadInfo;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api/fileServer")
public class FileController {
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private FileServiceImpl fileService;

    @GetMapping("/test")
    public void test(){
        System.out.println("111");
    }

    private String path = "../../../../nginx-1.21.4/html/";
    @PostMapping("/UpLoad")
    public String FileUpload(
            @RequestBody UpLoadInfo upLoadInfo
    ){
        //        System.out.println(upLoadInfo);
//        System.out.println("收到了消息");
//        ↓ 接下来应该处理upLoadInfo内部的信息了
        String name = upLoadInfo.getRealName();
//        先把data提取出来
        String base64 = upLoadInfo.getData();
        String[] base64s = StrUtil.splitToArray(base64, "base64,");
//        转换byte数组，↓ 这就是可以直接存储的数据！
        byte[] bytes = Base64.decode(base64s[1]);
//        ↓ 文件存储的名字
        String filename = IdUtil.getSnowflakeNextIdStr() + "_" + name;
        filename = filename.replace(" ", "_")
                .replace("\t", "_")
                .replace("\n", "_")
                .replace("\r", "_");
        upLoadInfo.setFileName(filename);
//        ↓ 文件的路径是需要确认的
        // 获取文件后缀
        int lastIndex = name.lastIndexOf('.');
        String suffix;
        if (lastIndex != -1 && lastIndex < name.length() - 1) {
            suffix = name.substring(lastIndex + 1);
//            System.out.println("文件后缀为: " + suffix);
            upLoadInfo.setSuffix(suffix);
        } else {
            suffix = "other";
//            System.out.println("无法获取文件后缀，文件名可能没有后缀");
            upLoadInfo.setSuffix(suffix);
        }
        String filePath =path +"/"+ suffix + "/";
        FileUtil.writeBytes(bytes, filePath + filename);
//        ↓ 存储完成之后，接下来就是将信息存储到数据库了
        filePath = suffix + "/";
        upLoadInfo.setFilePath(filePath);
        upLoadInfo.setLastUpDateTime(upLoadInfo.getTimeStamp());
        String virtualPath = upLoadInfo.getCreator() + "/root/upload/" + suffix;
        upLoadInfo.setVirtualPath(virtualPath);
        fileService.save(upLoadInfo);
        return filePath + filename;

    }

}
